const http = require('../../utils/http.js');
const app = getApp();
const regeneratorRuntime = require("../../utils/regenerator-runtime/runtime-module.js");
const { $Toast } = require('../../dist/base/index');
Page({

	/**
	 * 页面的初始数据
	 */
  data: {
    note: '',
    takeType: '',  //取快递或者寄快递 0取 1寄
    isWriteOrder: false,
    sizeIdx: 0,  //默认小件,
    kuaidiPrice: 0, //默认小件0元
    sizeArr: ['小件', '中件(加1元)', '超大件(加2元)'],
    kdNum: 1,
    pidx: '',
    paotuifeiArr: [],
    isclick: false, //防止点击多次提交按钮
  },

  //物品尺寸选择
  selectSize(e) {
    this.setData({
      sizeIdx: e.detail.value
    })

    if (this.data.sizeIdx == 0) {
      this.setData({
        kuaidiPrice: 0
      })
    } else if (this.data.sizeIdx == 1) {
      this.setData({
        kuaidiPrice: 1
      })
    } else if (this.data.sizeIdx == 2) {
      this.setData({
        kuaidiPrice: 2
      })
    }

    this.getPayPrice()
  },

  //快递数量填写
  fillNum(e) {
    console.log(e.detail.value);
    var kdNum = e.detail.value;
    kdNum < 0 ? kdNum = 1 : "";
    this.setData({
      kdNum
    })
    this.getPayPrice()
  },

  addOrder() {
    wx.showModal({
      content: '闪送超市加单可免费代取快递还可享受时效30分钟内送达，您需要加单吗',
      confirmColor: '#02BB00',
      cancelColor: '#888888',
      success(res) {
        // var shouhuoAddressId = wx.getStorageSync('nowAddress').school_id;
        // wx.setStorageSync('otherAddSchoolId', shouhuoAddressId)
        if (res.confirm) {
          wx.navigateTo({
            url: "/pages/FlashDelivery1/FlashDelivery1",
          })


        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })


  },
  //获取输入框内容
  getContent(e) {

    var note = e.detail.value;
    this.setData({
      note
    })
  },

  //选择红包
  chooseHongbao() {
    // if (this.data.paotuifei==0){

    // }
    wx.navigateTo({
      url: "../chooseHongBao/chooseHongBao",
    })
  },

  //提交订单
  submitOrder(e) {
    if (!this.data.isclick) {
      var formId = e.detail.formId;
      var uid = app.globalData.uid,
        sid = wx.getStorageSync('nowSchool').id,
        aid = wx.getStorageSync('nowAddress').id,
        paotuifie,
        redid = this.data.nowHongbao.pid || 0,
        note = this.data.note,
        orderType = this.data.orderType,
        orderSize = 0,
        orderNum = this.data.kdNum,
        orderAddId = this.data.jiadanId || 0,
        xiaofei = 0,
        total = this.data.payPrice;
      wx.request({
        url: app.globalData.host + 'procedure_t',
        method: 'post',
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        data: { p: 'R2013001|' + formId + '|' + uid }
      })
      wx.request({
        url: app.globalData.host + 'procedure_t',
        method: 'post',
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        data: { p: 'R2013001|' + formId + '|' + uid }
      })
      wx.request({
        url: app.globalData.host + 'procedure_t',
        method: 'post',
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        data: { p: 'R2013001|' + formId + '|' + uid }
      })
      wx.request({
        url: app.globalData.host + 'procedure_t',
        method: 'post',
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        data: { p: 'R2013001|' + formId + '|' + uid }
      })
      wx.request({
        url: app.globalData.host + 'procedure_t',
        method: 'post',
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        data: { p: 'R2013001|' + formId + '|' + uid },
        complete: () => {
          if (this.data.orderType == 1003) {
            paotuifie = this.data.paotuifei;
          } else if (this.data.orderType == 1002){
            paotuifie = this.data.platformFeer + this.data.kuaidiPrice;
          } else {
            paotuifie = this.data.platformFeer
          }
          //其他跑腿无加单
          orderType == '1003' ? orderAddId = 0 : ''
          console.log(paotuifie)

          if (!note) {
            console.log(this.data.takeType)
            switch (this.data.takeType) {
              case '0':
                $Toast({
                  content: '请填写取快递信息!'
                });
                break;
              case '1':
                $Toast({
                  content: '请填写寄快递信息!'
                });
                break;
              case '2':
                $Toast({
                  content: '请填写跑腿内容!'
                });
                break;
            }

            return
          }
          if (!orderNum) {
            $Toast({
              content: '请填写快件数量!'
            });
            return
          }
          if (!aid) {
            $Toast({
              content: '请填写地址!'
            });
            return
          }

          if (!this.data.pidx && this.data.orderType == 1003) {
            $Toast({
              content: '请选择跑腿费!'
            });
            return
          }

          // if (wx.getStorageSync('nowSchool').school_name !== wx.getStorageSync('nowAddress').school){
          //   wx.showModal({
          //     title: '提示',
          //     content: '收货地址与学校不一致，请选择正确的学校',
          //     showCancel:false,
          //     confirmText:'我知道了'
          //   })

          //   return
          // }

          http.fetchApi('procedure_t', { p: 'R2002004|' + uid + '|' + sid + '|' + aid + '|' + paotuifie + '|' + redid + '|' + note + '|' + orderType + '|' + orderSize + '|' + orderNum + '|' + orderAddId + '|' + xiaofei + '|' + total })
            .then(res => {
              if (res.data.code == 1) {

                //防止多次点击
                this.setData({
                  isclick: true
                })
                
                //当前订单id获取
                var orderId = res.data.results[0].orderid;
                var ddId = res.data.results[0].id;
                this.setData({
                  orderId
                })
                http.showToast('订单创建成功' + '', '', '').then(() => {

                  wx.removeStorageSync('totalPrice');
                  wx.removeStorageSync('jiadanId');
                  wx.removeStorageSync('hongbao');

                  setTimeout(() => {
                    wx.navigateTo({
                      url: '/pages/payment/payment?orderId=' + orderId + '&total=' + total + '&redid=' + redid + '&ddId=' + ddId
                    })
                  }, 500)
                })

              } else {
                // http.showToast('订单创建失败' + '', '', 'none')
                $Toast({
                  content: '订单创建失败!',
                  type: 'error'
                });
              }

            })
        }
      })
      
    }else{
      
      $Toast({
        content: '不能重复提交!',
        type: 'warning'
      });
    }

  },

  //计算需要支付的总价格
  getPayPrice() {

    //帮跑腿没有加单
    if (this.data.takeType == 2) {
      var totalPrice = 0;
    } else {
      var totalPrice = wx.getStorageSync('totalPrice') || 0; //加单商品价格  寄取快递才有
    }

    var hongbao = wx.getStorageSync('hongbao').jine || 0;
    //自定义跑腿费
    var paotuifei = this.data.paotuifei / 1 || 0;
    var kuaidiPrice = this.data.kuaidiPrice;
    //平台跑腿费
    var platformFeer = this.data.platformFeer / 1;
    var kdNum = this.data.kdNum;
    if (this.data.orderType == 1003) {
      //帮跑腿计算总价方法
      this.setData({
        payPrice: totalPrice - hongbao + paotuifei + kuaidiPrice < 0 ? 0 : totalPrice - hongbao + paotuifei + kuaidiPrice
      })
    } else if (this.data.orderType == 1002) {
      //寄快递计算总价方法
      if (totalPrice > 7) {
        this.setData({
          payPrice: totalPrice - hongbao + platformFeer < 0 ? 0 : totalPrice - hongbao + platformFeer
        })
      } else {
        this.setData({
          payPrice: totalPrice - hongbao + platformFeer + kuaidiPrice < 0 ? 0 : totalPrice - hongbao + platformFeer + kuaidiPrice
        })
      }


    } else if (this.data.orderType == 1001) {
      //取快递计算总价方法
      if (totalPrice > 7) {
        this.setData({
          payPrice: totalPrice - hongbao < 0 ? 0 : totalPrice - hongbao
        })
      } else {
        this.setData({
          payPrice: totalPrice - hongbao + (platformFeer * kdNum) + kuaidiPrice < 0 ? 0 : totalPrice - hongbao + (platformFeer * kdNum) + kuaidiPrice
        })
      }

      console.log(platformFeer * kdNum, this.data.payPrice)
    }


  },


  //获取跑腿费下拉选
  getPaotuifei() {
    http.fetchApi('procedure_t', { p: 'R2005006|' }).then(res => {
      if (res.data.code == 1) {
        var paotuifeiArr = res.data.results;
        this.setData({
          paotuifeiArr
        })
      }
    })
  },



  //选择跑腿费
  choosePaotuifei(e) {
    var paotuifeiArr = this.data.paotuifeiArr;
    var paotuifei = paotuifeiArr[e.detail.value].name == '免费' ? 0 : paotuifeiArr[e.detail.value].name;
    console.log(paotuifei)
    this.setData({
      pidx: e.detail.value,
      paotuifei
    })

    this.getPayPrice()
  },


  //获取取送快递跑腿费
  getPlatformFee() {
    var school_id = wx.getStorageSync('nowSchool').id;
    http.fetchApi('procedure_t', { p: 'R2012002|' + school_id }).then(res => {
      if (res.data.code == 1) {
        var platformFeer = res.data.results[0].ptf;
        this.setData({
          platformFeer
        })
        this.getPayPrice();
        app.globalData.platformFeer = platformFeer;
      }else{
        $Toast({
          content: '请开启地理位置授权',
          type: 'warning'
        });
      }
    })
  },

	/**
	 * 生命周期函数--监听页面加载
	 */
  onLoad: function (options) {
    var takeType = options.takeType;
    console.log(takeType)
    this.setData({
      takeType
    })

    if (takeType == 0) {
      wx.setNavigationBarTitle({
        title: '取快递'
      })
      this.setData({
        orderType: 1001
      })
    } else if (takeType == 1) {
      wx.setNavigationBarTitle({
        title: '寄快递'
      })
      this.setData({
        orderType: 1002
      })
    } else {
      wx.setNavigationBarTitle({
        title: '帮跑腿'
      })
      this.setData({
        orderType: 1003
      })
    }

    this.getPaotuifei();
    // this.setData({
    //   platformFeer:app.globalData.platformFeer
    // })

    // this.getPayPrice();
  },

  //选择收货地址
  chooseAddress() {
    wx.navigateTo({
      url: '../goodsAddress/goodsAddress?page=takeExpress',
    })
  },

  //快件大小页面
  toExpressSize() {
    wx.navigateTo({
      url: '../expressSize/expressSize',
    })
  },


	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
  onReady: function () {

  },

	/**
	 * 生命周期函数--监听页面显示
	 */
  onShow: function () {
    //取出加单的价格和商品
    var totalPrice = wx.getStorageSync('totalPrice');
    var jiadanId = wx.getStorageSync('jiadanId');
    var nowHongbao = wx.getStorageSync('hongbao');
    // var nowAddress = wx.getStorageSync('nowAddress');


    //取出默认地址放到地址栏
    var uid = app.globalData.uid;
    http.fetchApi('procedure_t', { p: 'R2003008|' + uid }).then(res => {
      if (res.data.code == 1) {
        var addressArr = res.data.results;
        var defaultAddress = addressArr.filter(item => item.isdefault);

        if (!wx.getStorageSync('nowAddress')) {
          console.log('没有地址')
          wx.setStorageSync('nowAddress', defaultAddress[0]);
          var nowAddress = wx.getStorageSync('nowAddress');

          this.setData({
            nowAddress
          })
        } else {
          var nowAddress = wx.getStorageSync('nowAddress');
          console.log('有地址')
          this.setData({
            nowAddress
          })
        }


      } else {
        $Toast({
          content: '服务器好像出错啦',
          type: 'error'
        });
        // http.showToast('服务器好像出错啦!' + '', '', 'none')
      }
    })

    this.setData({
      totalPrice,
      jiadanId,
      nowHongbao,
      // nowAddress
    })

    this.getPlatformFee();
    // this.getPayPrice();
  },

	/**
	 * 生命周期函数--监听页面隐藏
	 */
  onHide: function () {

  },

	/**
	 * 生命周期函数--监听页面卸载
	 */
  onUnload: function () {
    // wx.removeStorageSync('hongbao');
  },

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
  onPullDownRefresh: function () {

  },

	/**
	 * 页面上拉触底事件的处理函数
	 */
  onReachBottom: function () {

  },

	/**
	 * 用户点击右上角分享
	 */
  onShareAppMessage: function () {

  }
})
